//
//  MYRefreshView.swift
//  swift2.0项目开始
//
//  Created by 龚昕炜 on 16/8/4.
//  Copyright © 2016年 龚昕炜. All rights reserved.
//

import UIKit

/** 状态枚举值 */
enum MYRefreshStatus: Int {
    /** 正常状态 */
    case Normal = 1
    /** 下拉到可释放刷新 */
    case Pulling = 2
    /** 正在刷新 */
    case Loading = 3
}

class MYRefreshView: UIControl {
    
    var scrollView: UIScrollView?

    override init(frame: CGRect) {
        super.init(frame: frame)

        setUpUI()
    }
    
    /** 正在加载判断属性 */
    var isLoading: Bool {
        return loadingView.isAnimating()
    }
    
    /** 是否显示结束时label */
    var isShowEndLabel: Bool = false
    
    /** 控件状态 */
    var status: MYRefreshStatus = .Normal {
    
        didSet {
            
            /** 判断状态 */
            switch status {
            
                case .Normal:
                    /** 修改label内容 */
                    messageLabel.text = "下拉刷新"
                    /** 展示箭头 */
                    pictureView.hidden = false
                    /** 停止转动 */
                    loadingView.stopAnimating()
                    /** 隐藏菊花 */
                    loadingView.hidden = true
                    /** 转回方向 */
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        self.pictureView.transform = CGAffineTransformIdentity
                    })
                
                case .Pulling:
                    /** 修改label */
                    messageLabel.text = "释放刷新"
                    /** 修改方向 */
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        self.pictureView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                    })
                
                case .Loading:
                    /** 悬停一会 */
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        var insert = self.scrollView!.contentInset
                        insert.top = insert.top + 50
                        self.scrollView!.contentInset = insert
                    })
                    messageLabel.text = "加载中"
                    /** 隐藏箭头 */
                    pictureView.hidden = true
                    /** 菊花开始转动 */
                    loadingView.startAnimating()
                    /** 显示菊花 */
                    loadingView.hidden = false
                    
                    /**
                        接收事件相关的动作，理解：
                        1.一个控件可以添加事件并监听，就是外部添加事件，内部接收事件；
                        2.触发事件的条件出现时，外部触发，动作传入内部，内部接收到然后去外部响应事件；
                        3.联系：运行循环，响应者链；
                      */
                    sendActionsForControlEvents(.ValueChanged)
            }
            
        }
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)
        /** 如果是UIScrollView */
        if newSuperview is UIScrollView {
            /** 转换 */
            scrollView = newSuperview as? UIScrollView
            /** KVO监听值改变 */
            scrollView?.addObserver(self, forKeyPath: "contentOffset", options: .New, context: nil)
        }
    }
    
    var labelIsAnimating: Bool = false
    
    // MARK:-- 停止刷新
    func endReflashing() {
        /** 如果式正在刷新就移回刷新视图并改变当前状态 */
        if status == .Loading {
            UIView.animateWithDuration(0.25, animations: { () -> Void in

                var insert = self.scrollView!.contentInset
                insert.top = insert.top - 50
                self.scrollView?.contentInset = insert
                
                }, completion: { (_) -> Void in
                    
                    /** 如果要显示才显示 */
                    if (self.isShowEndLabel == false) && (self.labelIsAnimating == false) {
                        
                        self.showCountViewL.hidden = false
                        
                        self.labelIsAnimating = true
                        // 加动画
                        UIView.animateWithDuration(2, animations: { () -> Void in
                            // y值是让他的y值发生改变
                            self.showCountViewL.transform = CGAffineTransformMakeTranslation(0, 44)
                            }) { (_) -> Void in
                                
                                // 动画完成之后,再让他回去
                                UIView.animateWithDuration(2, animations: { () -> Void in
                                    //                    label.transform = CGAffineTransformMakeTranslation(0, 0)
                                    self.showCountViewL.transform = CGAffineTransformIdentity
                                    }, completion: { (_) -> Void in
                                        
                                        // 当完成之后, label 隐藏/移除
                                        self.showCountViewL.hidden = true
                                        self.labelIsAnimating = false
                                })
                        }
                    }
            })
        }
        status = .Normal
    }
    
    /** 实现监听方法 */
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        /** 正在拖拽 */
        if scrollView?.dragging == true {
        
            /** 临界值之前,并且是从pulling渐变回来 */
            if scrollView?.contentOffset.y > -140 && (status == .Pulling){
                self.status = .Normal
            } else if scrollView?.contentOffset.y < -140 && (status == .Normal){
                /** 临界值之后并且是从.Normal渐变回来 */
                /** 可释放刷新 */
                self.status = .Pulling
            }
        } else {
            /** 刷新 */
            if scrollView?.contentOffset.y < -140 && (status == .Pulling){
                self.status = .Loading
            }
        }
    }

    /** 创建控件设置布局 */
    private func setUpUI() {
        
        backgroundColor = UIColor.yellowColor()
        
        /** 位置大小 */
        var frame = self.frame
        frame.size = CGSize(width: screenBounds.width, height: 50)
        frame.origin.y = -50
        self.frame = frame
        
        /** 添加 */
        addSubview(pictureView)
        addSubview(messageLabel)
        addSubview(loadingView)
        addSubview(showCountViewL)
        showCountViewL.hidden = true
        
        /** 约束 */
        pictureView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self.snp_centerX).offset(-30)
            make.centerY.equalTo(self.snp_centerY)
        }
        
        messageLabel.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(pictureView.snp_right).offset(10)
            make.centerY.equalTo(self.snp_centerY)
        }
        
        loadingView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self.snp_centerX).offset(-30)
            make.centerY.equalTo(self.snp_centerY)
        }
        
    }
    
    // MARK:-- 懒加载
    private lazy var pictureView: UIImageView = {
    
        let img = UIImageView()
        
        img.image = UIImage(named: "tableview_pull_refresh")
        
        return img
    }()
    
    private lazy var messageLabel: UILabel = {
        
        let lbl = UILabel()
        
        lbl.text = "下拉刷新"
        
        return lbl
    }()
    
    private lazy var loadingView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
    
    private lazy var showCountViewL: UILabel = {
        
        let label = UILabel(frame: CGRect(x: 0, y: self.bounds.size.height - 44, width: self.bounds.size.width, height: 44))
        
//        label.bounds = CGRect(x: 0, y: 0, width: self.bounds.size.width, height: 44)
//        label.center = CGPoint(x: self.bounds.size.width * 0.5, y: <#T##CGFloat#>)
        label.text = "更新提示"
        
        label.backgroundColor = UIColor.orangeColor()
        
        label.textAlignment = .Center
        
        return label
    }()
    
}
